<?php
/**
 * 
 * Sign in and approve invitations
 * 
 * @category Abovo
 * 
 * @package Abovo_App_System
 * 
 * @subpackage Abovo_App_System_User
 * 
 * @author Antti Holvikari <anttih@gmail.com>
 * 
 */

/**
 * 
 * Sign in and approve invitations
 *
 * @category Abovo
 *
 * @package Abovo_App_System
 * 
 * @subpackage Abovo_App_System_User
 * 
 */
class Abovo_App_System_User extends Abovo_App_System {
    
    /**
     * 
     * undocumented class variable
     * 
     * @var string
     * 
     */
    protected $_Abovo_App_System_User = array(
        'layout' => 'signin',
    );
    
    /**
     * 
     * Default action
     * 
     * @var string
     * 
     */
    protected $_action_default = 'signIn';
    
    /**
     * 
     * Form for creating a new user
     * 
     * @var string
     * 
     */
    public $user_form;
    
    /**
     * 
     * Is invite approved
     * 
     * @var bool
     * 
     */
    public $approved = false;
    
    /**
     * 
     * Sign in
     * 
     * @return void
     * 
     */
    public function actionSignIn()
    {
        // add sign in style
        $this->layout_head['style'][] = 'Abovo/styles/signin.css';
        
        $this->layout_local['system/user/signin'] = $this->locale('APP_ACTION_SIGNIN');
        $this->layout_local_active = 'system/user/signin';
    }
    
    /**
     * Approve a user invitation and create an account
     * 
     * @return void
     */
    public function actionApprove($hash = null)
    {
        // don't continue if not valid hash 
        if (empty($hash) || strlen($hash) != 32) {
            return $this->_redirect('system/user');
        }
        
        $invite = Solar::factory('Abovo_Invite');
        
        // check if hash is valid
        if (! $invite->invites->isValid($hash)) {
            return $this->_redirect('system/user');
        }
        
        $contacts = Solar::factory('Abovo_Model_Contacts_Users');
        // fetch form, don't load company elements
        $form = $contacts->form();
        
        // add user elements
        $form = $this->_addUserElements($form);
        
        if ($this->_isProcess('go') && $form->validate()) {
            $values = $form->values();
            
            $contact = $values['contact'];
            $user    = $values['user'];
            
            // insert auth credentials
            $userdata = Solar::registry('auth')->insert($user);
            
            // add new user
            $contact['handle'] = $userdata['handle'];
            
            // add contact info
            $contacts->insert($contact);
            
            // approve the invitation
            $invite->invites->approve($hash);
            
            // tell view that we are done!
            $this->_view = 'approved';
            return;
        }
        
        // assign form for view
        $this->user_form = $form;
    }
    
    /**
     * Checks if passwords match
     * 
     * Matches $passwd against $_POST['user']['password']
     * 
     * @param string $passwd Password to match
     * 
     * @return bool
     */
    public function validatePasswdMatch($passwd)
    {
        // fetch $_POST['user]
        $user = $this->_request->post('user', false);
        
        // are the values set?
        if ($user && isset($user['password'])) {
            return $passwd == $user['password'] ? true : false;
        }
        
        return false;
    }
    
    /**
     * 
     * Builds the approval form
     * 
     * @param Solar_Form
     * 
     * @return Solar_Form
     * 
     */
    private function _addUserElements(Solar_Form $form)
    {
        // users model
        $users = Solar::registry('auth');
        
        // auth model data filter
        $filter = Solar::factory('Abovo_Model_Auth_DataFilter');
        
        // set handle element
        $form->setElement('user[handle]', array(
            'type'  => 'text',
            'label' => $users->locale('LABEL_HANDLE'),
            'filter' => array(
                array(
                    'callback',
                    $users->locale('VALID_HANDLE_RESERVED'),
                    array($users, 'validateUniqueHandle'),
                ),
                array(
                    'callback',
                    Solar::$locale->fetch('Abovo_Model_Auth', 'VALID_HANDLE'),
                    array($filter, 'validateHandle'),
                ),
            )
        ));
        
        // set handle element
        $form->setElement('user[password]', array(
            'type'  => 'password',
            'label' => $this->locale('LABEL_PASSWD'),
            'filter' => array(array(
                    'callback',
                    Solar::$locale->fetch('Abovo_Model_Auth', 'VALID_PASSWD'),
                    array($filter, 'validatePasswd'),
            )),
        ));
        
        // set password confirm element
        $form->setElement('user[password2]', array(
            'type'  => 'password',
            'label' => $this->locale('LABEL_PASSWD_CONFIRM'),
            'valid' => array(array(
                'callback',
                $this->locale('VALID_PASSWD_MATCH'),
                array($this, 'validatePasswdMatch'),
            ))
        ));
        
        $form->orderElements(array(
            'user[handle]',
            'user[password]',
            'user[password2]',
        ));
        
        // add submit button
        $form->setElement('process', array(
            'type'  => 'submit',
            'value' => $this->locale('PROCESS_GO'),
        ));
        
        return $form;
    }
    
    /**
     * 
     * Run before each action
     * 
     * @return void
     * 
     */
    protected function _preAction()
    {
        // users that are already signed in are not allowed here
        if (Solar::registry('user')->auth->isValid()) {
            $this->_redirect('/');
        }
    }
    
    /**
     * 
     * Set app info
     * 
     * @return void
     * 
     */
    protected function _preRun()
    {
        // override auth checks...
    }
}

